import imaplib

def fetch_latest_email_with_request(server, username, password):

    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL(server)

    # 登录到IMAP服务器
    mail.login(username, password)

    # 选择电子邮件箱
    mail.select("inbox")

    # 搜索电子邮件
    status, email_ids = mail.search(None, "ALL")
    email_ids = email_ids[0].split()

    # 获取每封电子邮件的内容
    for email_id in email_ids:
        status, email_data = mail.fetch(email_id, "(RFC822)")
        # 解析电子邮件
        # ...

    # 退出IMAP服务器
    mail.logout()

def test_fetch_latest_email(server, username, password):
    import poplib
    from email.parser import Parser

    # 连接POP3服务器
    pop_conn = poplib.POP3('pop.139.com:110')
    pop_conn.user('pc_cloudsync@139.com')
    pop_conn.pass_('caixun@111')

    # 获取邮件状态
    num_messages, total_size = pop_conn.stat()
    print(f"共有 {num_messages} 封邮件，总大小 {total_size} 字节")

    # 获取邮件列表
    messages = pop_conn.list()[1]
    for msg in messages:
        print(msg)

    # 获取第一封邮件
    resp, lines, octets = pop_conn.retr(1)
    msg_content = b'\n'.join(lines).decode('utf-8')
    msg = Parser().parsestr(msg_content)

    print(f"From: {msg['from']}")
    print(f"Subject: {msg['subject']}")
    print(f"Date: {msg['date']}")

    # 删除第一封邮件
    # pop_conn.dele(1)

    # 关闭连接
    pop_conn.quit()

if __name__ == '__main__':
    # 配置邮箱信息
    server = 'smtp.139.com:25'  # 替换为你的邮箱IMAP服务器
    username = 'pc_cloudsync@139.com'  # 替换为你的邮箱地址
    password = 'caixun@111'  # 替换为你的邮箱密码
    # username = 'chenkangfu139@139.com'  # 替换为你的邮箱地址
    # password = 'chenkf@123'  # 替换为你的邮箱密码

    # test_fetch_latest_email(server, username, password)
    test_fetch_latest_email(server, username, password)